package com.nexus.service.sys.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nexus.core.exception.ServiceException;
import com.nexus.core.service.BaseService;
import com.nexus.core.sys.entity.SysUser;
import com.nexus.core.sys.dto.SysUserDTO;
import com.nexus.service.sys.mapper.SysUserMapper;
import com.nexus.service.sys.service.mapstruct.SysUserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统用户Service
 *
 * @author 路正宁
 * @version 2023-03-16
 */
//@DS("zxhy_platform_db")
@Service
@Transactional(rollbackFor = {ServiceException.class,Exception.class, RuntimeException.class})
public class SysUserService extends BaseService<SysUserMapper, SysUser, SysUserDTO, SysUserWrapper> {


    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public SysUserDTO findById(String id) {
        return baseMapper.findById(id);
    }


    /**
     * 自定义分页检索
     *
     * @param page
     * @param queryWrapper
     * @return
     */
    public IPage<SysUserDTO> findPage(Page<SysUserDTO> page, QueryWrapper queryWrapper) {
        queryWrapper.eq("a.deleted", 0); // 排除已经删除
        return baseMapper.findList(page, queryWrapper);
    }

    public SysUserDTO findByLoginname(String loginNanme){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("a.login_name", loginNanme);
        IPage<SysUserDTO> page = findPage(new Page<>(1, 1), queryWrapper);
        if(ObjectUtil.isNotEmpty(page.getRecords())){
            return page.getRecords().getFirst();
        }
        return null;
    }

    /**
     * 用户登录
     * @author luzhengning
     * @date 2023/3/20 14:28
     */
    public SysUserDTO userLogin(String username,String password) throws ServiceException {
        SysUserDTO sysUserDTO = baseMapper.userLogin(username, password);
        return sysUserDTO;
    }
    /**
     * 修改密码
     * @author luzhengning
     * @date 2023/3/21 15:33
     */
    public boolean updatePassword(String userId, String newPwd){
        int i = baseMapper.updatePassword(userId, newPwd);
        return i>0;
    }

}
